<script setup lang="ts">
  import { computed, ref, watch } from 'vue'
  import {
    getUserRelationCodeGoodsList,
    getUserRelationInfo,
    getUserRelationOrderList,
  } from '@/api/users'
  import { ElMessage, TabsPaneContext } from 'element-plus'
  import { tableHeaderCellStyle } from '@/utils/tools'
  import Pagination from '@/components/Pagination/index.vue'
  import { UserRelationGood, UserRelationInfoDetail, UserRelationOrder } from './types'

  const props = defineProps({
    userName: {
      type: String,
      required: true,
    },
    orderId: {
      type: String,
      required: true,
    },
  })

  // 工单id
  const workId = ref('')

  // 公司关联
  const activeUserName = ref('userRelationGoods')

  // 抽屉显示状态
  const drawerVisible = ref(false)

  /**
   * 显示公司关联信息抽屉
   */
  const onShow = async () => {
    drawerVisible.value = true
    await getUserRelationInfoData()
  }

  // 公司工单产品信息
  const userRelationInfoDetail = ref<UserRelationInfoDetail | null>(null)

  // 根据工单ID获取公司关联信息加载
  const getUserRelationInfoDataLoading = ref(false)

  // 根据工单ID获取公司关联信息方法
  const getUserRelationInfoData = async () => {
    if (workId.value) {
      getUserRelationInfoDataLoading.value = true
      const res = await getUserRelationInfo(workId.value)
      if (res.data.success) {
        userRelationInfoDetail.value = res.data.data.row
        await getUserRelationGoods()
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 3000,
        })
      }
      getUserRelationInfoDataLoading.value = false
    }
  }

  // 关联产品分页组件实例
  const paginationGoods = ref<InstanceType<typeof Pagination> | null>(null)

  // 公司关联产品列表
  const UserRelationCodeGoodsList = ref<{ rows: Array<UserRelationGood>; total: number }>({
    rows: [],
    total: 0,
  })

  // 获取公司关联产品列表加载
  const getUserRelationGoodsLoading = ref(false)

  /**
   * 获取公司关联产品列表
   */
  const getUserRelationGoods = async () => {
    if (!userRelationInfoDetail.value) {
      return false
    }
    let data = {
      limit: paginationGoods.value.size || 50,
      page: paginationGoods.value.current || 1,
    }
    getUserRelationGoodsLoading.value = true
    const res = await getUserRelationCodeGoodsList(data, userRelationInfoDetail.value.userId)
    if (res.data.success) {
      UserRelationCodeGoodsList.value = res.data.data
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 3000,
      })
    }
    getUserRelationGoodsLoading.value = false
  }

  // 公司关联工单分页组件实例
  const paginationOrder = ref<InstanceType<typeof Pagination> | null>(null)

  // 获取公司关联工单列表
  const UserRelationOrderList = ref<{ rows: Array<UserRelationOrder>; total: number }>({
    rows: [],
    total: 0,
  })

  // 获取公司关联工单加载
  const getUserRelationOrdersLoading = ref(false)

  /**
   * 获取公司关联工单
   */
  const getUserRelationOrders = async () => {
    if (!userRelationInfoDetail.value) {
      return false
    }
    const data = {
      limit: paginationOrder.value.size || 50,
      page: paginationOrder.value.current || 1,
    }
    getUserRelationOrdersLoading.value = true
    const res = await getUserRelationOrderList(data, userRelationInfoDetail.value.userId)
    if (res.data.success) {
      UserRelationOrderList.value = res.data.data
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 3000,
      })
    }
    getUserRelationOrdersLoading.value = false
  }

  /**
   * 标签点击事件
   * @param {TabsPaneContext} pane 标签点击事件参数
   */
  const handleTableClick = (pane: TabsPaneContext) => {
    if (pane.props.name === 'userRelationOrders') {
      getUserRelationOrders()
    }

    if (pane.props.name === 'userRelationGoods') {
      getUserRelationGoods()
    }
  }

  const hDrawerLoading = computed(() => {
    return (
      getUserRelationOrdersLoading.value ||
      getUserRelationGoodsLoading.value ||
      getUserRelationInfoDataLoading.value
    )
  })

  watch(
    () => props.orderId,
    (value) => {
      workId.value = value
    },
    { immediate: true },
  )
</script>

<template>
  <div style="display: flex; align-items: center">
    <!-- <HLink @click="onShow">{{ props.userName || '' }}</HLink> -->
    <div>{{ props.userName || '' }}</div>

    <h-drawer v-model="drawerVisible" :loading="hDrawerLoading" :width="60">
      <template #title>
        <div class="title">
          <span class="text">公司关联档案表</span>
          <i class="iconfont icon-refresh_2" @click="getUserRelationInfoData"></i>
          <div class="tip">
            <div class="dot"></div>
            <div class="text">点击刷新</div>
          </div>
        </div>
      </template>

      <div class="body">
        <div v-if="userRelationInfoDetail" class="info_list">
          <div class="info_item">
            <div class="label">公司名称</div>
            <div class="value">{{ userRelationInfoDetail.userName }}</div>
          </div>
          <div class="info_item">
            <div class="label">联系人电话</div>
            <div class="value">{{ userRelationInfoDetail.userPhone }}</div>
          </div>
          <div class="info_item">
            <div class="label">关联工单量</div>
            <div class="value">{{ userRelationInfoDetail.orderQty }}</div>
          </div>
          <div class="info_item">
            <div class="label">关联产品量</div>
            <div class="value">{{ userRelationInfoDetail.goodsQty }}</div>
          </div>
          <div class="info_item">
            <div class="label">创建时间</div>
            <div class="value">{{ userRelationInfoDetail.userCreateTime }}</div>
          </div>
          <div class="info_item">
            <div class="label">公司条码</div>
            <div class="value">{{ userRelationInfoDetail.userCode }}</div>
          </div>
        </div>
        <el-tabs v-model="activeUserName" @tab-click="handleTableClick">
          <!-- 关联产品 -->
          <el-tab-pane
            :label="`关联产品（${userRelationInfoDetail?.goodsQty}）`"
            name="userRelationGoods"
          >
            <div class="product_table_container">
              <el-table
                :border="true"
                :data="UserRelationCodeGoodsList.rows"
                resizable
                stripe
                :header-cell-style="tableHeaderCellStyle"
              >
                <template #empty>
                  <el-empty description="暂无数据" />
                </template>
                <el-table-column
                  label="序号"
                  width="55"
                  type="index"
                  :align="'center'"
                  fixed="left"
                />
                <el-table-column show-overflow-tooltip label="产品信息">
                  <template #default="scope">
                    {{ scope.row.goodsBrand }}&nbsp;{{ scope.row.goodsName }}&nbsp;{{
                      scope.row.goodsModel
                    }}&nbsp;{{ scope.row.goodsSpecName }}
                  </template>
                </el-table-column>
                <el-table-column prop="code" show-overflow-tooltip label="产品编号" width="180" />
                <el-table-column
                  prop="registerTime"
                  show-overflow-tooltip
                  label="登记时间"
                  width="150"
                />
                <el-table-column
                  prop="status"
                  label="状态"
                  width="70"
                  fixed="right"
                  :align="'center'"
                >
                  <template #default="scope">
                    <HStatus v-if="scope.row.status !== 2" type="info">禁用</HStatus>
                    <HStatus v-else>启用</HStatus>
                  </template>
                </el-table-column>
              </el-table>
              <div class="footer">
                <Pagination
                  ref="paginationGoods"
                  :list_total="Number(UserRelationCodeGoodsList?.total || 0)"
                  @size-change="getUserRelationGoods"
                  @current-change="getUserRelationGoods"
                />
              </div>
            </div>
          </el-tab-pane>

          <!-- 关联工单 -->
          <el-tab-pane
            :label="`关联工单（${userRelationInfoDetail?.orderQty}）`"
            name="userRelationOrders"
          >
            <div class="order_list">
              <el-table
                v-loading="getUserRelationOrdersLoading"
                :border="true"
                :data="UserRelationOrderList.rows"
                resizable
                stripe
                :header-cell-style="tableHeaderCellStyle"
              >
                <template #empty>
                  <el-empty description="暂无数据" />
                </template>
                <el-table-column
                  label="序号"
                  width="55"
                  type="index"
                  fixed="left"
                  :align="'center'"
                />
                <el-table-column
                  prop="workNo"
                  show-overflow-tooltip
                  label="工单条码"
                  width="180"
                />
                <el-table-column show-overflow-tooltip label="产品信息">
                  <template #default="scope">
                    {{ scope.row.goodsBrand }}&nbsp;{{ scope.row.goodsName }}&nbsp;{{
                      scope.row.goodsModel
                    }}&nbsp;{{ scope.row.goodsSpecName }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  show-overflow-tooltip
                  label="创建时间"
                  width="150"
                />
                <el-table-column
                  prop="endTime"
                  show-overflow-tooltip
                  label="完成时间"
                  width="150"
                />
                <el-table-column
                  prop="status"
                  label="状态"
                  width="120"
                  fixed="right"
                  :align="'center'"
                >
                  <template #default="scope">
                    <div class="flex_justify_center">
                      <HStatus v-if="scope.row.status === 1" type="warning">待派单</HStatus>
                      <HStatus v-if="scope.row.status === 2" type="warning">待网点确认</HStatus>
                      <HStatus v-if="scope.row.status === 3" type="warning">处理中</HStatus>
                      <HStatus v-if="scope.row.status === 4" type="success">已完成</HStatus>
                      <HStatus v-if="scope.row.status === 5" type="info">已取消</HStatus>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <div class="footer">
                <Pagination
                  ref="paginationOrder"
                  :list_total="Number(UserRelationOrderList?.total || 0)"
                  @size-change="getUserRelationOrders"
                  @current-change="getUserRelationOrders"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </h-drawer>
  </div>
</template>

<style scoped lang="scss">
  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  .title {
    display: flex;
    align-items: center;
    gap: 5px;

    .text {
      font-size: 16px;
    }

    .iconfont {
      cursor: pointer;

      &:hover {
        //.iconfont {
        color: $primaryColor;
        animation: spin 1s linear infinite;
        //}
      }
    }

    .tip {
      width: 60px;
      height: 22px;
      box-sizing: border-box;
      background: #fff;
      border: 1px solid #e4e7ed;
      position: relative;
      margin-left: 4px;
      border-radius: 2px;

      .text {
        font-size: 12px;
        text-align: center;
        line-height: 20px;
        color: $primaryColor;
      }

      .dot {
        width: 10px;
        height: 10px;
        transform: translate(-50%, -50%);
        top: 50%;
        position: absolute;

        &::after {
          content: ' ';
          position: absolute;
          width: 10px;
          height: 10px;
          z-index: -1;
          transform: rotate(45deg);
          background-color: #fff;
          border-left: 1px solid #e4e7ed;
          border-bottom: 1px solid #e4e7ed;
          box-sizing: border-box;
        }
      }
    }
  }

  .body {
    height: 100%;

    .info_list {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;

      .info_item {
        display: flex;
        flex-direction: column;
        row-gap: 6px;

        .label {
          color: #606266;
        }
      }
    }

    :deep(.el-tabs) {
      height: calc(100% - 58px);

      .el-tabs__header {
        margin-bottom: 12px;
      }

      .el-tabs__content {
        height: calc(100% - 52px);

        .el-tab-pane {
          height: 100%;

          .product_table_container,
          .order_list {
            height: 100%;
            display: flex;
            flex-direction: column;
            gap: 12px;

            .footer {
              display: flex;
              justify-content: flex-end;
              padding-bottom: 12px;
            }
          }
        }
      }
    }
  }
</style>
